package com.zlyx.easy.security.tokenstore.redis.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;

import com.zlyx.easy.core.config.AppConfig;
import com.zlyx.easy.core.utils.StringUtils;

/**
 * <p>
 * 基于Redis作为TokenStore配置
 * </p>
 *
 * @author 赵光
 * @version v1.0
 */
@Order(-1)
public class RedisTokenStoreConfig {

	protected Logger logger = LoggerFactory.getLogger(SecurityConfigurerAdapter.class);

	public static final String REDIS_TOKEN_PREFIX = "redis.token.prefix";

	@Autowired(required = false)
	private RedisTokenStoreSerializationStrategy redisTokenStoreSerializationStrategy;

	@Bean
	public TokenStore tokenStore(RedisConnectionFactory redisConnectionFactory) {
		return new RedisTokenStore(redisConnectionFactory) {
			{
				String prefix = System.getProperty(REDIS_TOKEN_PREFIX, AppConfig.getName());
				if (StringUtils.isNotBlank(prefix)) {
					this.setPrefix(prefix + ":");
				}
				if (redisTokenStoreSerializationStrategy != null) {
					this.setSerializationStrategy(redisTokenStoreSerializationStrategy);
				}
			}
		};
	}

}